package com.briup.estore.web.servlet;

import com.briup.estore.bean.ShopCart;
import com.briup.estore.bean.extend.ShopCartExtend;
import com.briup.estore.service.Impl.ShopCartServiceImpl;
import com.briup.estore.service.ShopCartService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/**
 * 添加购物车
 */
@WebServlet("/addBookToShopCart")
public class AddShopCartServlet extends HttpServlet {
    private ShopCartService shopCartService;
    {
        shopCartService=new ShopCartServiceImpl();
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取参数
        String bookId = req.getParameter("book_id");
        String  userIdstr = req.getParameter("user_id");
        String num=req.getParameter("num");
        //检查
        Integer userId;
        if(userIdstr == null || "".equals(userIdstr)){
             userId=Integer.parseInt((String) req.getAttribute("userId"));
        }else{
            userId=Integer.parseInt(userIdstr);
        }
        //封装成对象传给后台
        ShopCart shopCart=new ShopCart();
        shopCart.setBookId(Integer.parseInt(bookId));
        shopCart.setUserId(userId);
        shopCart.setNum(Integer.parseInt(num));
        //新增
        shopCartService.addBook2ShopCart(shopCart);
        //查询，保存
        List<ShopCartExtend> shopCartList = shopCartService.findShopCartDetailByUserId(userId);
        HttpSession session=req.getSession();
        session.setAttribute("shopCartList",shopCartList);
        //跳转
        resp.sendRedirect("shopCart");

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
